<?php
	header("content-type: text/xml");
	require_once '../includes/Config.inc.php';
	
	$cfg = Config::getInstance('..');
	$fb_desktop = $cfg->getFacebookDesktop();
	$Smarty = $cfg->getSmarty();
	$orange = new OrangeAPI($cfg->or_api_key);
	
	if($orange->isMMS()) {						// MMS receive
		
		$mms = $orange->fetchMMS("./attachment/");
		$user = User::getUserByPhone($mms->from);
		
		if($user !== false) {
		
			$filename = '';
			$type = '';
			$text = '';
		
			foreach($mms->files as $file) {
			
				if($file['type'] == 'text')
					$text = $file['content'];
				else {
					if($file['type'] == 'image') {
						$type = 'image';
						$filename = $file['name'];
					}
					elseif($file['type'] == 'video') {
						$type = 'flash';
						$filename = $file['name'];
					}
					elseif($file['type'] == 'audio') {
						$type = 'mp3';
						$filename = $file['name'];
					}
				}
			}
		
			$attachment = array('href' => 'http://test.aurelienguillard.com/orange/backend/attachment/'.$filename,
					'description' => addslashes($text),
					'media' => array(array('type' => $type,
							'src' => 'http://test.aurelienguillard.com/orange/backend/attachment/'.$filename,
							'href' => 'http://test.aurelienguillard.com/orange/backend/attachment/'.$filename))
			);
			$json_attachment = json_encode($attachment);
		
			$fb_desktop->set_user($user->fb_id, $user->fb_session);
			$fb_desktop->set_session_secret($user->fb_secret);
			$fb_desktop->api_client->stream_publish($mms->subject, $json_attachment);
		
			$Smarty->assign('status', 'ok');
			$Smarty->assign('message', $mms->subject);
		
		}
		else {
			$Smarty->assign('status', 'error');
			$Smarty->assign('message', "phone number not in the database");
		}	
	}
	elseif($orange->isSMS()) {
		
		$sms = $orange->fetchSMS();
		
		$user = User::getUserByPhone($sms->from);
		
		if($user !== false) {
			// TWITTER
			$twitter = $cfg->getTwitter($user->tw_token, $user->tw_secret);
			$twitter->OAuthRequest('https://twitter.com/statuses/update.xml', array('status' => $sms->text), 'POST');
		
			//FACEBOOK
			$fb_desktop->set_user($user->fb_id, $user->fb_session);
			$fb_desktop->set_session_secret($user->fb_secret);
			$fb_desktop->api_client->stream_publish($sms->text);
		
			$Smarty->assign('status', 'ok');
			$Smarty->assign('message', $sms->text);
		}
		else {
			$Smarty->assign('status', 'error');
			$Smarty->assign('message', "phone number not in the database");
		}
	}
	
	function logString($text) {
		$handle = fopen("log.txt", "a+");
	    if(!fwrite($handle, date("F j, Y, g:i a") . " : " . $text . chr(10))) {
			xmlOut("error", "erreur d'écriture dans le fichier de log");
			
		}
		fclose($handle);
	
	}
	
	$Smarty->display('receivesms.tpl');
?>
